package com.oywy.rbac.service;

import com.oywy.rbac.entity.Role;
import com.oywy.rbac.entity.User;
import com.oywy.rbac.repository.RoleRepository;
import com.oywy.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.Collection;
import java.util.List;

/**
 * 用户服务
 *
 * @author oywy
 * @date 2018/10/22
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserService implements UserDetailsService {
    @Autowired
    private UserRepository userRepo;
    @Autowired
    private RoleRepository roleRepo;

    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException {
        return userRepo.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException(username));
    }

    public int grantRoleByUsername(String username, Collection<String> roleIds) {
        User user = this.loadUserByUsername(username);
        Collection<Role> roles = roleRepo.findAllById(roleIds);
        user.setRoles(roles);
        userRepo.save(user);
        return roles.size();
    }
    public int grantRole(String id, Collection<String> roleIds) {
        List<Role> roles = roleRepo.findAllById(roleIds);
        User user = userRepo.findById(id).orElseThrow(NullPointerException::new);
        user.setRoles(roles);
        userRepo.save(user);
        return roles.size();
    }

    public List<User> listUser() {
        return userRepo.findAll();
    }

    public User get(String id) {
        return userRepo.findById(id).orElseThrow(EntityNotFoundException::new);
    }
    public User post(User user){
        return userRepo.save(user);
    }
    public User put(User user){
        return userRepo.save(user);
    }
    public void del(String id){
        userRepo.deleteById(id);
    }
}
